import React, { Suspense, useEffect } from 'react';
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import { Spin } from 'antd';
import MainLayout from '../components/Layout';
import PlatformLayout from '../components/PlatformLayout';
import PermissionGuard from '../components/PermissionGuard';
import { usePlatformStore } from '../stores/platform';
import PlatformPermissionGuard from '../components/PlatformPermissionGuard';
import { setGlobalNavigate } from '../utils/navigation';

// 懒加载页面组件
const Dashboard = React.lazy(() => import('../pages/Dashboard'));
const Users = React.lazy(() => import('../pages/Users'));
const Roles = React.lazy(() => import('../pages/Roles'));
const Teams = React.lazy(() => import('../pages/Teams'));
const Departments = React.lazy(() => import('../pages/Departments'));
const Permissions = React.lazy(() => import('../pages/Permissions'));
const Menus = React.lazy(() => import('../pages/Menus'));
const Profile = React.lazy(() => import('../pages/Profile'));
const Settings = React.lazy(() => import('../pages/Settings'));
const Login = React.lazy(() => import('../pages/Login'));
const PlatformLogin = React.lazy(() => import('../pages/PlatformLogin'));

const TenantManagement = React.lazy(() => import('../pages/TenantManagement'));
const PlatformDashboard = React.lazy(() => import('../pages/PlatformDashboard'));
const PlatformUsers = React.lazy(() => import('../pages/PlatformUsers'));
const PlatformRoles = React.lazy(() => import('../pages/PlatformRoles'));
const PlatformPermissions = React.lazy(() => import('../pages/PlatformPermissions'));
const PlatformSettings = React.lazy(() => import('../pages/PlatformSettings'));
const PlatformTickets = React.lazy(() => import('../pages/PlatformTickets'));


const NotFound = React.lazy(() => import('../pages/NotFound'));

// 加载中组件
const PageLoading: React.FC = () => (
  <div style={{ 
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center', 
    height: '200px' 
  }}>
    <Spin size="large" />
  </div>
);

// 开发环境检查
const isDevelopment = import.meta.env.DEV;

// 私有路由组件 - 在开发环境下简化检查
const PrivateRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  if (isDevelopment) {
    return <>{children}</>;
  }
  
  const token = localStorage.getItem('token');
  return token ? <>{children}</> : <Navigate to="/login" replace />;
};

// 平台管理私有路由组件
const PlatformPrivateRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isAuthenticated } = usePlatformStore();
  
  if (isDevelopment) {
    // 开发环境下直接允许访问
    return <>{children}</>;
  }
  
  return isAuthenticated ? <>{children}</> : <Navigate to="/platform-login" replace />;
};

// 权限包装组件 - 在开发环境下跳过权限检查
const DevPermissionGuard: React.FC<{
  children: React.ReactNode;
  requiredPermissions?: string[];
  requiredRoles?: string[];
}> = ({ children, requiredPermissions, requiredRoles }) => {
  if (isDevelopment) {
    // 开发环境下直接渲染子组件
    return <>{children}</>;
  }
  
  return (
    <PermissionGuard 
      requiredPermissions={requiredPermissions}
      requiredRoles={requiredRoles}
      skipInDev={true}
    >
      {children}
    </PermissionGuard>
  );
};

// 路由配置
export const AppRoutes: React.FC = () => {
  const navigate = useNavigate();
  
  // 设置全局导航函数，供axios拦截器使用
  useEffect(() => {
    setGlobalNavigate(navigate);
  }, [navigate]);
  
  return (
    <Suspense fallback={<PageLoading />}>
      <Routes>
        {/* 保持后端提供的真实路径，不做前端重写 */}

        {/* 登录页面 */}
        <Route path="/login" element={<Login />} />
        
        {/* 平台管理员登录页面 */}
        <Route path="/platform-login" element={<PlatformLogin />} />
        
        {/* 主应用路由 */}
        <Route
          path="/"
          element={
            <PrivateRoute>
              <MainLayout />
            </PrivateRoute>
          }
        >
          {/* 默认重定向到仪表盘 */}
          <Route index element={<Navigate to="/dashboard" replace />} />
          
          {/* 仪表盘 - 所有登录用户都可访问 */}
          <Route 
            path="dashboard" 
            element={
              <Suspense fallback={<PageLoading />}>
                <Dashboard />
              </Suspense>
            } 
          />
          
          {/* 别名路由 - 与后端菜单路径保持一致 */}
          <Route 
            path="home" 
            element={
              <Suspense fallback={<PageLoading />}>
                <Dashboard />
              </Suspense>
            } 
          />
          <Route 
            path="system/users" 
            element={
              <DevPermissionGuard requiredPermissions={['user:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Users />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="system/roles" 
            element={
              <DevPermissionGuard requiredPermissions={['role:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Roles />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="system/teams" 
            element={
              <DevPermissionGuard requiredPermissions={['team:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Teams />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="system/departments" 
            element={
              <DevPermissionGuard requiredPermissions={['department:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Departments />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="system/permissions" 
            element={
              <DevPermissionGuard requiredRoles={['admin']}>
                <Suspense fallback={<PageLoading />}>
                  <Permissions />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="system/menus" 
            element={
              <DevPermissionGuard requiredPermissions={['menu:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Menus />
                </Suspense>
              </DevPermissionGuard>
            } 
          />

          {/* 保留无前缀的原路由，避免已有入口失效 */}
          <Route 
            path="users" 
            element={
              <DevPermissionGuard requiredPermissions={['user:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Users />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="roles" 
            element={
              <DevPermissionGuard requiredPermissions={['role:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Roles />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="teams" 
            element={
              <DevPermissionGuard requiredPermissions={['team:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Teams />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="departments" 
            element={
              <DevPermissionGuard requiredPermissions={['department:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Departments />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="permissions" 
            element={
              <DevPermissionGuard requiredRoles={['admin']}>
                <Suspense fallback={<PageLoading />}>
                  <Permissions />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          <Route 
            path="menus" 
            element={
              <DevPermissionGuard requiredPermissions={['menu:read']}>
                <Suspense fallback={<PageLoading />}>
                  <Menus />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
          
          {/* 个人资料 - 所有登录用户都可访问 */}
          <Route 
            path="profile" 
            element={
              <Suspense fallback={<PageLoading />}>
                <Profile />
              </Suspense>
            } 
          />
          
          {/* 系统设置 - 需要管理员角色 */}
          <Route 
            path="settings" 
            element={
              <DevPermissionGuard requiredRoles={['admin']}>
                <Suspense fallback={<PageLoading />}>
                  <Settings />
                </Suspense>
              </DevPermissionGuard>
            } 
          />
        </Route>
        
        {/* 平台管理路由 */}
        <Route
          path="/platform"
          element={
            <PlatformPrivateRoute>
              <PlatformLayout />
            </PlatformPrivateRoute>
          }
        >
          {/* 默认重定向到平台仪表盘 */}
          <Route index element={<Navigate to="/platform/dashboard" replace />} />
          
          {/* 平台仪表盘 */}
          <Route 
            path="dashboard" 
            element={
              <Suspense fallback={<PageLoading />}>
                <PlatformDashboard />
              </Suspense>
            } 
          />
          
          {/* 租户管理 */}
          <Route 
            path="tenants" 
            element={
              <PlatformPermissionGuard requiredPermissions={['platform:tenant:read']}>
                <Suspense fallback={<PageLoading />}>
                  <TenantManagement />
                </Suspense>
              </PlatformPermissionGuard>
            } 
          />
          
          {/* 平台用户管理 */}
          <Route 
            path="users" 
            element={
              <Suspense fallback={<PageLoading />}>
                <PlatformUsers />
              </Suspense>
            } 
          />
          
          {/* 平台角色管理 */}
          <Route 
            path="roles" 
            element={
              <Suspense fallback={<PageLoading />}>
                <PlatformRoles />
              </Suspense>
            } 
          />
          
          {/* 平台权限管理 */}
          <Route 
            path="permissions" 
            element={
              <Suspense fallback={<PageLoading />}>
                <PlatformPermissions />
              </Suspense>
            } 
          />
          
          {/* 平台设置 */}
          <Route 
            path="settings" 
            element={
              <Suspense fallback={<PageLoading />}>
                <PlatformSettings />
              </Suspense>
            } 
          />
          
          {/* 工单管理 */}
          <Route 
            path="tickets" 
            element={
              <Suspense fallback={<PageLoading />}>
                <PlatformTickets />
              </Suspense>
            } 
          />
          
          {/* 平台个人资料 */}
          <Route 
            path="profile" 
            element={
              <Suspense fallback={<PageLoading />}>
                <Profile />
              </Suspense>
            } 
          />
          
          {/* 平台系统设置 */}
          <Route 
            path="settings"
            element={
              <Suspense fallback={<PageLoading />}>
                <Settings />
              </Suspense>
            } 
          />
        </Route>
        
        {/* 404页面 */}
        <Route 
          path="*" 
          element={
            <Suspense fallback={<PageLoading />}>
              <NotFound />
            </Suspense>
          } 
        />
      </Routes>
    </Suspense>
  );
};

export default AppRoutes;